<!--
 * @description  : 案件-证据先行登记保存通知书文书
 * @descriptionDetail: 案件-证据先行登记保存通知书书
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-08-24 15:43:11
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
      <view class="white-color" @click="printOrDown(state.canEdit)">
        {{ state.canEdit?'预览':'打印' }}
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="state.canEdit?fContent:fContents" @fabtrigger="fabtrigger" />
		<!-- #endif -->
		<view class="main-content">
			<view style="width: calc(100% - 30px);">
				<form-section title="证据先行登记保存通知书"></form-section>
			</view>
			<u-form class="form-content" :model="docGoodsReg" :error-type="errorType" ref="uForm">
        <u-form-item label="文书编号" :label-position="labelPosition" :required="true" prop="fullDocNo">
          <u-input
            placeholder="请填写文书编号"
            :disabled="!state.canEdit"
            v-model="docGoodsReg.fullDocNo"
          />
        </u-form-item>
        <u-form-item label="当事人" :label-width="labelWidth" :required="true" right-icon="arrow-right">
          <u-input placeholder="请输入" input-align="right" :disabled="!state.canEdit" v-model="docGoodsReg.party" @click="()=>{if(state.canEdit) partySelectShow = true}" />
        </u-form-item>
        <u-form-item
          label="案由"
          :label-position="labelPosition"
          :required="true"
          right-icon="arrow-right"
          prop="causeOfAction"
          ref="caseChangeRef"
        >
          <u-input
            type="textarea"
            height="35"
            :auto-height="true"
            placeholder="请选择"
            :disabled="true"
            v-model="docGoodsReg.causeOfAction"
            @click="()=>{if(state.canEdit) causeOfActionHandle()}"
          />
        </u-form-item>
        <u-form-item label="违反条例" :label-position="labelPosition" prop="illegalRequire">
          <u-input
            placeholder="请输入违反条例"
            type="textarea"
            height="35"
            :auto-height="true"
            :disabled="!state.canEdit"
            v-model="docGoodsReg.illegalRequire"
          />
        </u-form-item>
        <u-form-item label="处罚条例" :label-position="labelPosition" prop="illegalClause">
          <u-input
            placeholder="请输入处罚条例"
            type="textarea"
            height="35"
            :auto-height="true"
            :disabled="!state.canEdit"
            v-model="docGoodsReg.illegalClause"
          />
        </u-form-item>
        <u-form-item label="" :label-position="labelPosition">
          <show-goods-info
            :caseUuid="caseParam.caseUuid"
            :dataFromInit="getGoodsApvDtl"
            :hasDel="state.canEdit"
            ref="goodInfoRef"
          >
          </show-goods-info>
        </u-form-item>
        <u-form-item>
          <view class="person-info">
            <view class="p-title">
              <view class="doc-sub-required">
                *
              </view>
              <view class="doc-sub-title">
                承办人
              </view>
              <view class="uicon-sty" @click="()=>{if(state.canEdit) addPerson()}">
                <u-icon name="plus-circle" :color="$theme.u_type_primary" size="40"></u-icon>
              </view>
            </view>
            <view class="p-content" v-for="(item,index) in personList" :key="index">
              <text class="p-width">
                {{ item.personName }}
              </text>
              <text>
                {{ item.leCertNo || item.inspectionCertNo }}
              </text>
            </view>
          </view>
        </u-form-item>
        <u-form-item
          :required="true"
          :label-width="labelWidth"
          label="文书日期"
          right-icon="arrow-right"
          prop="regTime"
          ref="endChangeRef"
        >
          <u-input
            placeholder="请选择文书日期"
            :disabled="true"
            input-align="right"
            v-model="docGoodsReg.regTime"
            @click="clicDatekHandle('isShowCyEnd')"
          />
        </u-form-item>
				<u-form-item label="送达方式" :required="true" :label-position="labelPosition" prop="deliveryStyle">
          <dic-input
            :keyWord="$u.dic.DIC_KEYS.BSC_SERVICE_TYPE"
            :dicCode="docGoodsReg.deliveryStyle"
            inputAlign="left"
            type="select"
            :select-open="dicSelectOpen('deliveryStyle', $u.dic.DIC_KEYS.BSC_SERVICE_TYPE)"
            placeholder="请选择"
            v-model="docGoodsReg.deliveryStyleName"
            @changeInputModelData="(name) => {$set(docGoodsReg, 'deliveryStyleName', name);}"
            @click="showDic($u.dic.DIC_KEYS.BSC_SERVICE_TYPE,docGoodsReg.deliveryStyle,'deliveryStyle')"
          />
        </u-form-item>
        <u-form-item label="送达地点" label-width="200" :required="true" prop="deliveryAddr">
          <u-input type='textarea' height="35" :auto-height="true" placeholder="请输入送达地点" :disabled="!state.canEdit" v-model="docGoodsReg.deliveryAddr" />
        </u-form-item>
        <u-form-item label="复议机关" :label-position="labelPosition">
          <u-input placeholder="请输入复议机关" :disabled="!state.canEdit" v-model="docGoodsReg.recheckOrg" />
        </u-form-item>
        <u-form-item label="起诉法院" :label-position="labelPosition">
          <u-input placeholder="请输入起诉法院" :disabled="!state.canEdit" v-model="docGoodsReg.courtName" />
        </u-form-item>
        <u-form-item :label-position="labelPosition" label="备注">
          <u-input
            type="textarea"
            placeholder="请填写备注"
            :disabled="!state.canEdit"
            v-model="docGoodsReg.memo"
          />
        </u-form-item>
      </u-form>
    </view>
    <!-- 底部按钮开始 -->
    <view class="submit-btns btn-other-cls" v-if="state.canEdit">
      <u-button plain class="u-btn" type="primary" @click="saveOrSubmit('save')">
        保存
      </u-button>
      <u-button class="u-btn" type="primary" @click="saveOrSubmit('submit')">
        提交
      </u-button>
    </view>
    <!-- 底部按钮结束 -->
    <!-- 人员选择 -->
    <u-popup mode="bottom" height="80%" v-model="personSelectShow">
      <person-selection :params="psParam" @choose="handlerChoosePerson"></person-selection>
    </u-popup>
    <u-calendar :mode="mode" :max-date="yestDate" v-model="isShowCyEnd" @change="changeDate('regTime',$event)">
    </u-calendar>
    <u-popup mode="bottom" height="80%" v-model="partySelectShow">
      <select-party-component :params="partyParams" @choose="handlerChooseParty"></select-party-component>
    </u-popup>
		<dic-choice :keyWord="dicKeyWords" :currentSelect="dicCurrentSelect" v-model="dicShow" @confirm="selectDicConfirm" />
  </view>
</template>
<script>
	import { dateUtils } from "@/common/util";
	import DicInput from "@/components/dic_input.vue"
	import DicChoice from "@/components/dic_choice.vue"
	import PersonSelection from "@/pages/case/components/personSelection.vue";
	import caseCommon from "../caseCommonMixin.js";
	import ShowDocRegGoodsInfo from "@/pages/case/components/showDocRegGoodsInfo.vue";
	import {	DOC_STATUS } from "@/common/common_enum.js";
	import officeService from "@/service/case/office.service.js";
	import zjCommonService from "@/service/common/common.service";
	import SelectPartyComponent from "../components/selectPartyComponent.vue";
	import caseService from "@/service/case/case.service";
	import FormSection from "@/components/form-section.vue";
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			"show-goods-info": ShowDocRegGoodsInfo,
			PersonSelection,
			SelectPartyComponent,
			FormSection,
			fabButton,
			DicInput,
			DicChoice
		},
		mixins: [caseCommon, ],
		data() {
			return {
				DOC_STATUS,
				dicShow: false,
				personSelectShow: false,
				mode: 'date',
				maxDate: '2099-12-31',
				isShowCyEnd: false,
				labelWidth: '180',
				isDisabled: false, // 表单是否禁用
				rules: {
					// 当事人
					party: [{
						required: true,
						message: '请输入当事人',
						trigger: ['change', 'blur', ],
					}, ],
					// 案由
					causeOfAction: [{
						required: true,
						message: '请选择案由',
						trigger: ['change', 'blur', ],
					}, ],
					fullDocNo: [{
						required: true,
						message: '请填写文书编号',
						trigger: 'change',
					}, ],
					regTime: [{
						required: true,
						message: '请选择文书日期',
						trigger: ['change', 'blur', ],
					}],
					deliveryStyle: [{
						required: true,
						message: "请选择送达方式",
						trigger: ["change", "blur"],
					}],
					deliveryAddr: [{
						required: true,
						message: '请输入送达地点',
						trigger: ['change', 'blur', ],
					}]
				},
				dicKeyWords:'',
				dicCurrentSelect:'02',
				errorType: ['border-bottom', 'message', ],
				labelPosition: "top",
				isAction: false,
				psParam: {},
				goodsList: [],
				caseParam: {}, // 文书列表中传过来的参数
				doc: {},
				docGoodsReg: {},
				personList: [], // 承办人
				saveData: {}, // 保存后的数据
				btnType: "",
				partySelectShow: false,
				partyList: [], // 当事人列表
				partyParams: {}, // 传给当事人选择页面的参数
				yestDate: this.$u.timeFormat(Date.now()),
				fromInDoc: true,
				fContent: [{
					iconPath: require('@/static/oview.png'),
					selectedIconPath: require('@/static/oview.png'),
					text: '预览',
					active: false,
				}],
				fContents: [{
					iconPath: require('@/static/dy.png'),
					selectedIconPath: require('@/static/dy.png'),
					text: '打印',
					active: false,
				}]
			}
		},
		watch: {
			isAction(newValue, oldValue) {
				this.$refs.caseChangeRef.validation();
			},
			isShowCyEnd(newValue, oldValue) {
				this.$refs.endChangeRef.validation();
			},
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad() {
			this.caseParam = this.getRouteParam();
			this.caseParam.justUnUse = 'true';
			console.log('fuck==' + JSON.stringify(this.caseParam));
		},
		mounted() {
			this.docStep((docInfo) => {
				this.doc = docInfo ? docInfo : {};
				this.setRightBtns();
			});
			this.initDocData();
		},
		methods: {
			// 设置右侧标题
			setRightBtns() {
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight(this.state.canEdit ? '预览' : '打印', () => {
					this.printOrDown(this.state.canEdit);
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.printOrDown(this.state.canEdit);
				}
			},
			// 初始化文书信息
			initDocData() {
				let parms = {
					id: this.caseParam.id,
					docUuid: this.caseParam.docUuid,
					bizUuid: this.caseParam.bizUuid,
				}
				this.fromInDoc = true;
				officeService.docInfo(parms).then(res => {
					let [employeeList, rs, ] = [
						[], {},
					];
					if (res.success && res.data.length === 2) {
						rs = res.data[1];
						employeeList = this.parseEmployee(rs);
						rs.goodsRegUuid = res.data[0].goodsRegUuid;
						rs.regTime = !rs.regTime ? dateUtils.dateFormat("yyyy年MM月dd日", new Date()) : rs.regTime;
						this.goodsList = [...res.data[0].goods, ].length == 0 ? undefined : [...res.data[0]
							.goods,
						];
					} else {
						rs = res.data[0];
						employeeList = this.parseEmployee(rs);
						rs.regTime = !rs.regTime ? dateUtils.dateFormat("yyyy年MM月dd日", new Date()) : rs.regTime;
						this.goodsList = [...rs.goods, ].length == 0 ? undefined : [...rs.goods, ];
					}
					this.$refs['goodInfoRef'].setStaticData(this.goodsList);
					this.fromInDoc = false;
					this.docGoodsReg = rs;
					this.personList = employeeList;
					this.$u.hideLoading();
					this.getPartyInfoList();
				}).catch(err => {
					this.$u.toast(err);
				});
			},
			// 数据字典组件选择事件
			dicSelectOpen(keyWord) {
				if (this.dicKeyWords == keyWord && this.dicShow) {
					return true;
				}
				return false;
			},
			showDic(key, cur, fileName) {
				if (!this.state.canEdit) return;
				if (this.dicShow) return;
				this.dicKeyWords = key;
				this.dicCurrentSelect = cur;
				this.dicShow = true;
			},
			selectDicConfirm(e) {
				if (this.dicKeyWords == this.$u.dic.DIC_KEYS.BSC_SERVICE_TYPE) {
					this.docGoodsReg.deliveryStyleName = e[0].label;
					this.docGoodsReg.deliveryStyle = e[0].extra.bcbCode;
				}
			},
			// 获取当事人list（多选）
			getPartyInfoList() {
				caseService.getPartyInfoList(this.caseParam.bizUuid).then(res => {
					if (!res.success) return;
					this.partyList = res.data.length > 0 ? res.data : [];
					this.partyList.forEach(itm => {
						if (this.docGoodsReg.partyUuids.indexOf(itm.partyUuid) != -1) {
							itm.check = true;
						}
					});
					this.partyParams = {
						list: this.partyList,
						selUsersStr: this.docGoodsReg.partyUuids,
					}
					this.$u.hideLoading();
				}).catch((err) => {
					this.$u.hideLoading();
					this.partyList = [];
					console.log(err);
				});
			},
			// 选择当事人回调事件
			handlerChooseParty(e) {
				this.partySelectShow = false;
				this.docGoodsReg.party = e.partyNames;
				this.partyParams.selUsersStr = e.partyUuids;
				this.docGoodsReg.partyUuids = e.partyUuids;
			},
			getGoodsApvDtl() {
				return new Promise((resolve, reject) => {
					if (this.fromInDoc) {
						resolve({
							noPage: 1,
							data: this.goodsList,
						});
						return;
					}
					caseService.getGoodsApvDtl({
						caseUuid: this.caseParam.caseUuid,
					}).then(res => {
						this.goodsList = !res.success ? [] : [...res.data, ];
						resolve({
							noPage: 1,
							data: this.goodsList,
						});
					}).catch(e => {
						this.goodsList = [];
						resolve({
							noPage: 1,
							data: this.goodsList,
						});
					});
				});
			},
			clicDatekHandle(type) {
				if (!this.state.canEdit) return;
				this[type] = true;
			},
			changeDate(type, e) {
				this.docGoodsReg[type] = dateUtils.dateFormat("yyyy年MM月dd日", new Date(e.result));
			},
			// 案由点击事件
			causeOfActionHandle() {
				this.isAction = true;
				this.$u.route('pages/case/components/casePropertySelection');
			},
			// 选择案由、承办人、物品清单返回的数据
			updateBackState(param) {
				// 案由
				if (param.caseSelectionData) {
					let [names, ids, ] = [
						[],
						[],
						[],
						[],
					];
					param.caseSelectionData.forEach((item) => {
						names.push(item.caseProperty);
						ids.push(item.casepropUuid);
					});
					this.$set(this.docGoodsReg, 'causeOfAction', names.join(","));
					this.$set(this.docGoodsReg, 'casepropIds', ids.join(","));
					this.isAction = false;
				}
				// 物品清单
				if (param.refresh) {
					this.$refs['goodInfoRef'].updateBackState(param);
				}
			},
			// 表单验证
			validForm(type) {
				let basicValid = false;
				this.btnType = type;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						if (!this.docGoodsReg.party) {
							this.$u.toast('请选择当事人!');
							return;
						}
						basicValid = true;
					} else {
						basicValid = false;
					}
				});
				return basicValid;
			},
			// 保存或提交
			saveOrSubmit(type) {
				if (type == 'preview') {
					if (!this.doc.isRecorded) {
						this.$u.toast('请先保存数据');
						return;
					}
					officeService.buildLocalPunish("/record/doc-goods-reg", this.doc.docInsUuid).then(pdfId => {
						if (pdfId.success) {
							this.downloadFile(pdfId.bean, "预览", false);
						} else {
							this.$u.toast(pdfId.msg);
						}
					});
				} else {
					let flag = this.validForm(type);
					if (flag) {
						if (this.personList.length == 0) {
							this.$u.toast('请选择承办人!');
							return;
						}
						if (this.docGoodsReg.docNo.length > 20) {
							this.$u.toast('文书编号请输入20位以内的字符!');
							return;
						}
						this.handleOperBtn(type);
					}
				}
			},
			handleOperBtn(type) {
				if (this.$refs.goodInfoRef.goodsList.length == 0) {
					this.$u.toast('物品信息不能为空!');
					return;
				}
				let [docGoodsReg, goodsLst, self, ] = [this.docGoodsReg, this.$refs.goodInfoRef.goodsList, this, ];
				docGoodsReg.goods = goodsLst;
				docGoodsReg.caseUuid = this.caseParam.bizUuid;
				this.$modal.confirm(`确定${type === 'submit' ? '提交' : '保存'}吗？`, () => {
					type === 'save' && this.$u.loading('数据保存中...');
					officeService.saveGoodsReg(this.docGoodsReg, this.caseParam.docUuid, this.caseParam.titemUuid)
						.then((res) => {
							this.$u.hideLoading();
							if (res.success) {
								this.$u.toast(res.msg);
								let [data, bean, ] = [res.data[0], res.bean, ];
								docGoodsReg.goodsRegUuid = data.docInsUuid;
								docGoodsReg.docUuid = data.docUuid;
								docGoodsReg.titemUuid = data.configIns.titemUuid;
								docGoodsReg.goodsApvUuid = bean.goodsApvUuid;
								goodsLst = bean.goods;
								this.saveData = data;
								self.doc['isRecorded'] = res.data[0].isRecorded;
								self.doc['docInsUuid'] = res.data[0].docInsUuid;
								this.docGoodsReg = docGoodsReg;
								this.goodsList = [...goodsLst, ];
								if (type === 'submit') {
									this.$u.loading('数据提交中...');
									officeService.submitDoc(data.docUuid, data.docInsUuid, data.configIns
										.titemUuid, bean).then(res => {
										this.$u.hideLoading();
										this.saveBehaviorLog(1, this.caseParam, this.doc);
										if (res.success) {
											// 返回列表
											this.$u.toast(res.msg);
											self.backPrev({
												paramKey: "offiList",
												param: {
													caseUuid: this.caseParam.bizUuid,
													caseCode: this.caseParam.caseCode,
													caseType: this.caseParam.caseType,
												},
											});
										} else {
											this.$u.toast(res.msg);
										}
									})
								} else {
									this.saveBehaviorLog(0, this.caseParam, this.doc);
								}
							} else {
								this.$u.toast(res.msg);
							}
						});
				});
			},
			// 打印/预览
			printOrDown(flag) {
				if (flag) {
					// 调接口预览
					this.saveOrSubmit('preview');
				} else {
					this.downloadFile(this.doc.pdfFileId);
				}
			},
			downloadFile(fileId, titleName, isDownload) {
				let pdfIds = fileId;
				if (!pdfIds) {
					this.$u.toast("没有文书");
					return;
				}
				this.setRouteParam({
					fileId: pdfIds,
					fileName: titleName,
					isDownload: isDownload,
				});
				this.$u.route('pages/commonPage/printerComponent');
			},
			// 添加承办人事件
			addPerson() {
				this.psParam = {
					min: 2,
					max: 2,
					caseUuid: this.caseParam.caseUuid,
				};
				this.personSelectShow = true;
			},
			handlerChoosePerson(e) {
				this.personSelectShow = false;
				this.personList = [...e, ];
				let tIds = [];
				let tNames = [];
				this.personList.forEach(el => {
					tIds.push(el.personUuid);
					tNames.push(el.personName + "(" + el.leCertNo + ")");
				});
				this.docGoodsReg['undertakerUuids'] = tIds.join(",");
				this.docGoodsReg['undertaker'] = tNames.join(",");
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import "../case_common.scss";

	.page {
		padding: 0;
	}

	.doc-no {
		display: inline-block;
		height: 35px;
		width: 60px;
		text-align: center !important;
		flex: none;
	}

	.desc-btm {
		font-size: 13px;
		color: #333;
	}
</style>
